﻿using Microsoft.Extensions.DependencyInjection;
using HSGD.Common;

namespace HSGD.Extensions.ServiceExtensions {
    public static class CorsSetup {

        public static void AddCorsSetup(this IServiceCollection services) {
            if (services == null) {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddCors(c => {
                if (!AppSettings.app(["Startup", "Cors", "EnableAllIPs"]).ObjToBool()) {
                    c.AddPolicy(AppSettings.app(["Startup", "Cors", "PolicyName"]),
                        policy => {

                            policy
                            .WithOrigins(AppSettings.app(["Startup", "Cors", "IPs"]).Split(','))
                            .AllowAnyHeader()//Ensures that the policy allows any header.
                            .AllowAnyMethod();
                        });
                }
                else {
                    //允许任意跨域请求
                    c.AddPolicy(AppSettings.app(["Startup", "Cors", "PolicyName"]),
                        policy => {
                            policy
                            .SetIsOriginAllowed((host) => true)
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials();
                        });
                }
            });
        }
    }
}
